// import { mapState, mapMutations } from "vuex";
import { getSort, getInfo, getNewsList, getMyRankInfo } from '../../api/activity/index';
import request from '@/api/index';
// var haveShop = false;
const documentElement = document.documentElement;
const body = document.body;
export default {
  name: "index",
  data() {
    return {
      id:'',
      NavList: ["日","周", "月","季","年","累计"],
      selected:0,
      NavDayList: ["周一","周二","周三","周四","周五","周六","周日"],
      NavItemList:[],
      selecteItem:0,
      page: 1,
      last_page: 0,
      content:'',
      info:'',
      activity_start_time:'',
      activity_end_time:'',
      name:'',
      banner:'',
      contentShow:false,
      userList:[],
      myTime:false,
      selectTime:[],
      my_start_time:'',
      my_end_time:'',
      isAll:0,
      type: 0, // 活动类型，1时显示"活动商品"文字
      showActivityGoods: false, // 是否显示活动商品文字
      activityGoodsNewLine: false, // 活动商品是否另起一行显示
      tabSon: { width: '5px' }, // tab样式配置
      // 资讯相关
      newsList: [],
      // 我的排名信息
      myRank: '-', // 我的排名，从后台获取
      myInfo: {
        avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
        nickname: '我的昵称',
        uid: '10000',
        amount: 0
      },
      showMyRank: false, // 是否显示我的排名（接口返回数据后才显示）
      // UID重试相关
      uidCheckTimer: null, // 定时器
      uidCheckCount: 0, // 已检查次数
      maxUidCheckCount: 10, // 最大检查次数
      // 排行榜人数相关
      activityCount: null, // 从getInfo接口获取的activity_count数据
      showRankTip: false, // 是否显示排行榜人数提示
      currentRankCount: 0 // 当前时间类型对应的人数
    };
  },
  computed: {
  },
  created(){
    this.id = this.$route.query.id;
    this.getInfo();
    this.getNewsListData(); // 获取资讯列表
  },
  mounted(){
    // this.getSort();
    
    this.getDayList();
    // this.getMonthList();
    
    // 延迟获取rules-content的宽度，确保DOM完全渲染
    // setTimeout(() => {
    //   this.getRulesContentWidth();
    // }, 100);
    
    // 监听窗口大小变化
    // window.addEventListener('resize', () => {
    //   this.getRulesContentWidth();
    // });
    
    // 开始检查UID并获取排名
    this.startCheckUidAndGetRank();
  },
  beforeDestroy() {
    // 清理事件监听器
    window.removeEventListener('resize', this.getRulesContentWidth);
    
    // 清理定时器
    if (this.uidCheckTimer) {
      clearInterval(this.uidCheckTimer);
      this.uidCheckTimer = null;
    }
  },
  methods: {
    // 获取rules-content宽度信息
    getRulesContentWidth() {
      this.$nextTick(() => {
        const rulesContent = document.querySelector('.rules-content');
        if (rulesContent) {
          // 获取元素的各种宽度
          const offsetWidth = rulesContent.offsetWidth;
          const clientWidth = rulesContent.clientWidth;
          const scrollWidth = rulesContent.scrollWidth;
          
          // 获取计算后的样式
          const computedStyle = window.getComputedStyle(rulesContent);
          const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;
          const paddingRight = parseFloat(computedStyle.paddingRight) || 0;
          const borderLeft = parseFloat(computedStyle.borderLeftWidth) || 0;
          const borderRight = parseFloat(computedStyle.borderRightWidth) || 0;
          
          // 计算实际内容宽度
          const contentWidth = clientWidth - paddingLeft - paddingRight;
          
          // 获取父容器信息
          const parentElement = rulesContent.parentElement;
          const parentWidth = parentElement ? parentElement.offsetWidth : 0;
          
          // 获取活动卡片信息
          const activityCard = document.querySelector('.activity-card');
          const cardWidth = activityCard ? activityCard.offsetWidth : 0;
          const cardClientWidth = activityCard ? activityCard.clientWidth : 0;
          
          console.log('=== 详细宽度信息 ===');
          console.log('rules-content offsetWidth:', offsetWidth + 'px');
          console.log('rules-content clientWidth:', clientWidth + 'px');
          console.log('rules-content scrollWidth:', scrollWidth + 'px');
          console.log('rules-content paddingLeft:', paddingLeft + 'px');
          console.log('rules-content paddingRight:', paddingRight + 'px');
          console.log('rules-content borderLeft:', borderLeft + 'px');
          console.log('rules-content borderRight:', borderRight + 'px');
          console.log('实际内容宽度:', contentWidth + 'px');
          console.log('父容器宽度:', parentWidth + 'px');
          console.log('活动卡片宽度:', cardWidth + 'px');
          console.log('活动卡片clientWidth:', cardClientWidth + 'px');
          console.log('窗口宽度:', window.innerWidth + 'px');
          console.log('屏幕宽度:', screen.width + 'px');
          console.log('========================');
        } else {
          console.log('未找到rules-content元素');
        }
      });
    },
    
    // 检查p标签的实际行数并设置activityGoodsNewLine
    checkActualLines() {
      this.$nextTick(() => {
        // 只有在显示活动商品时才进行检查
        if (!this.showActivityGoods || !this.info) {
          return;
        }
        
        const rulesContent = document.querySelector('.rules-content');
        if (!rulesContent) {
          console.log('未找到rules-content元素');
          return;
        }
        
        const pElement = rulesContent.querySelector('p');
        if (!pElement) {
          console.log('未找到p标签');
          return;
        }
        
        // 获取p标签的实际高度和行高
        const pHeight = pElement.offsetHeight;
        const computedStyle = window.getComputedStyle(pElement);
        const lineHeight = parseFloat(computedStyle.lineHeight) || 22.4;
        
        // 计算实际行数
        const actualLines = Math.round((pHeight / lineHeight) * 10) / 10; // 保留一位小数
        
        // 计算预期行数（基于字符数和容器宽度）
        const containerWidth = this.getContainerWidth();
        const charWidth = 14; // 假设字符宽度
        const charsPerLine = Math.floor(containerWidth / charWidth) - 5;
        const expectedLines = Math.ceil(this.info.length / charsPerLine);
        
        console.log('=== 活动商品换行判断 ===');
        console.log('p标签高度:', pHeight + 'px');
        console.log('行高:', lineHeight + 'px');
        console.log('实际行数:', actualLines);
        console.log('预期行数:', expectedLines);
        console.log('info内容:', this.info);
        console.log('info长度:', this.info.length);
        console.log('容器宽度:', containerWidth + 'px');
        console.log('每行字符数:', charsPerLine);
        
        // 判断是否需要换行
        const needsNewLine = Math.abs(actualLines - expectedLines) > 0.1;
        this.activityGoodsNewLine = needsNewLine;
        
        if (needsNewLine) {
          console.log('✓ 实际行数与预期行数不一致，活动商品需要换行显示');
        } else {
          console.log('✓ 实际行数与预期行数一致，活动商品可以同行显示');
        }
        console.log('最终结果 - activityGoodsNewLine:', this.activityGoodsNewLine);
        console.log('==================================');
      });
    },
    
    searchTime(){
      this.isAll = 0;
      this.start_time = new Date(this.my_start_time).getTime();
      this.end_time = new Date(this.my_end_time).getTime()+(24*60*60-1)*1000;
      this.getSort();
    },
    getSort() {
      // 根据时间类型获取对应的type参数
      const typeMap = {
        0: 'day',      // 日
        1: 'week',     // 周
        2: 'month',    // 月
        3: 'quarter',  // 季
        4: 'year',     // 年
        5: 'total'     // 累计
      };
      
      let param={
        'id':this.id,
        'start_time':this.start_time,
        'isAll':this.isAll,
        'end_time':this.end_time,
        'type': typeMap[this.selected] || 'day' // 添加type参数
      };
      let toast=this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0,
      });
      getSort(param).then(res => {
        if(res.result==1){
          this.userList = res.data;
          toast.clear();
          console.log(this.selecteItem);
          
          // 排行榜加载完成后，检查并更新我的排名
          this.checkMyRankInList();
        }
      });
      
      
    },
    getInfo(){
      let param={
        'id':this.id,
      };
      let toast=this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0,
      });
      getInfo(param).then(res => {
        if(res.result==1){
        this.content = res.data.content;
        this.info = res.data.info;
        this.activity_start_time = res.data.activity_start_time;
        this.activity_end_time = res.data.activity_end_time;
        this.real_start_time = res.data.start_time;
        this.real_end_time = res.data.end_time;
        this.name = res.data.name;
        this.banner = res.data.banner;
        this.type = res.data.type; // 设置活动类型
        this.activityCount = res.data.activity_count; // 保存activity_count数据
        toast.clear();
        
        // 初始化排行榜人数提示
        this.updateRankTip();
      }
      });
      

    },
    swichTabTItem() { //上级时间
      this.keywords = "";
      this.isAll = 0;
      this.my_start_time = '';
      this.my_end_time = '';
      this.selecteItem = 0;
      // window.scrollTo(0, 0);
      this.page = 1;
      this.userList = [];
      
      console.log('🔄 切换一级时间，selected:', this.selected);
      
      // 更新排行榜人数提示
      this.updateRankTip();
      
      if(this.selected ==0){
        this.getDayList();
      }
      if(this.selected ==1){
        this.getWeekList();
      }
      if(this.selected ==2){
        this.getMonthList();
      }
      if(this.selected ==3){
        this.getQuarterList();
      }
      if(this.selected ==4){
        this.getYearList();
      }
      if(this.selected ==5){
        this.isAll = 1;
        this.getAllList();
      }
      
      // this.getOutboundList();
    },
    swichTabTItem2() { //二级时间
      this.keywords = "";
      this.my_start_time = '';
      this.my_end_time = '';
      this.userList = [];
      console.log(this.NavItemList[this.selecteItem]);
      // window.scrollTo(0, 0);
      this.page = 1;
      
      console.log('🔄 切换二级时间，selecteItem:', this.selecteItem);
      
      // 检查NavItemList和selecteItem是否有效
      if (this.NavItemList && this.NavItemList[this.selecteItem]) {
        this.start_time = this.NavItemList[this.selecteItem].star_time;
        this.end_time = this.NavItemList[this.selecteItem].end_time;
        this.getSort();
      } else {
        console.warn('NavItemList或selecteItem无效:', {
          NavItemList: this.NavItemList,
          selecteItem: this.selecteItem
        });
      }
      console.log(this.selecteItem);
    },
    getDay(){
      let date = new Date();
      let weekIndex = date.getDay();
      console.log(weekIndex);
      if(weekIndex ==0){
        weekIndex=7;
      }
      this.selecteItem = weekIndex-1;
      
    },
    getDayList(){
      this.NavItemList=[];
      var today = new Date();
      today.setHours(0, 0, 0, 0);

      // let time = this.weekCheckingIn();
      // let start_time = time.MondayTime;
      // let end_time = time.MondayTime+(24*60*60-1)*1000;
      //获取一周的数据
      for(let i=0; i<7; i++) {
        let previousDay = new Date(today);
        previousDay.setDate(today.getDate()-i);
        let data ={
          star_time:previousDay.getTime(),
          end_time:previousDay.getTime()+(24*60*60-1)*1000,
          title:previousDay.getDate()+'号'
        };
        this.NavItemList.push(data);
      }
      console.log(this.NavItemList);
      // //设置默认值
      // let date = new Date();
      // let weekIndex = date.getDay();
      // console.log(weekIndex);
      // if(weekIndex ==0){
      //   weekIndex=7;
      // }
      // this.$nextTick(() => {
      //   this.selecteItem = weekIndex-1;
      //   this.start_time = this.NavItemList[this.selecteItem].star_time;
      //   this.end_time = this.NavItemList[this.selecteItem].end_time;
      // });
      if (this.NavItemList && this.NavItemList[this.selecteItem]) {
        this.start_time = this.NavItemList[this.selecteItem].star_time;
        this.end_time = this.NavItemList[this.selecteItem].end_time;
        this.getSort();
      }
    },
    getWeekList(){
      this.NavItemList=[];
      
      // 检查real_start_time是否存在
      if (!this.real_start_time) {
        console.warn('real_start_time未定义，无法获取周数据');
        return;
      }
      
      //先取开始时间的下周一
      console.log('real_start_time:', this.real_start_time);
      let WeekMonday = this.getWeekMonday(this.real_start_time*1000);
      console.log('WeekMonday:', WeekMonday);
      
      //获取当前距离周一的周数
      let Weeknum = this.getNowWeek(WeekMonday);
      console.log('Weeknum:', Weeknum);
      
      // let Weeknum = this.getNowWeek(1758463600000);
      //获取本周的周一和周日
      let time = this.weekCheckingIn();
      let MondayTime = time.MondayTime;
      let SundayTime = time.SundayTime;
      console.log('MondayTime:', MondayTime, 'SundayTime:', SundayTime);
      
      //判断是否有5周，大于等于5周显示5周，小于5周显示实际周数
      console.log('开始循环，Weeknum:', Weeknum);
      for(let i=0; i<Weeknum; i++) {
        let data ={
          star_time:MondayTime-1000 * 60 * 60 * 24*7*i,
          end_time:SundayTime-1000 * 60 * 60 * 24*7*i,
          title:'第'+(Weeknum-i)+'周'
        };
        console.log('添加周数据:', data);
        this.NavItemList.push(data);
        if(i==4){
          console.log('达到最大周数限制，跳出循环');
          break;
        }
      }
      console.log('循环结束，NavItemList长度:', this.NavItemList.length);
      
      console.log('NavItemList:', this.NavItemList);
      
      if (this.NavItemList && this.NavItemList[0]) {
        this.start_time = this.NavItemList[0].star_time;
        this.end_time = this.NavItemList[0].end_time;
        console.log('准备发送请求:', { start_time: this.start_time, end_time: this.end_time });
        this.getSort();
      } else {
        console.warn('NavItemList为空或第一个元素不存在');
      }
      console.log(Weeknum);
    },
    getMonthList(){
      this.NavItemList=[];
      this.start_time = this.real_start_time*1000;
      let today = new Date();
      let year = today.getFullYear();
      let lastMonth = today.getMonth();
      let firstMonth = new Date(this.start_time).getMonth();
      for(let i=lastMonth; i>firstMonth-1; i--) {
        let data ={
          star_time:new Date(year,i, 1).getTime(),
          end_time:new Date(year,i+1, 0).getTime()+(24*60*60-1)*1000,
          title:(i+1)+'月'
        };
        this.NavItemList.push(data);
        if(i==4){
          break;
        }
      }
      if(this.NavItemList.length==0){
        let data ={
          star_time:new Date(year,lastMonth, 1).getTime(),
          end_time:new Date(year,lastMonth+1, 0).getTime()+(24*60*60-1)*1000,
          title:(lastMonth+1)+'月'
        };
        
        this.NavItemList.push(data);
      }
      if (this.NavItemList && this.NavItemList[0]) {
        this.start_time = this.NavItemList[0].star_time;
        this.end_time = this.NavItemList[0].end_time;
        this.getSort();
      }
    },
    getQuarterList(){
      this.NavItemList=[];
      let today = new Date();
      let year = today.getFullYear();
      for(let i=4; i>0; i--) {
        let data ={
          isAll:this.isAll,
          star_time:new Date(year,(i-1)*3, 1).getTime(),
          end_time:new Date(year,i*3, 0).getTime()+(24*60*60-1)*1000,
          title:year+'-'+i+'季度'
        };
        this.NavItemList.push(data);
      }
      const month = new Date().getMonth() + 1;
      let index2 = 4-Math.ceil(month / 3);
      if (this.NavItemList && this.NavItemList[index2]) {
        this.start_time = this.NavItemList[index2].star_time;
        this.end_time = this.NavItemList[index2].end_time;
        console.log(index2);
        this.$nextTick(() => {
          this.selecteItem=Number(index2);
        });
      }
      
      this.getSort();
    },
    getYearList(){
      this.NavItemList=[];
      let today = new Date();
      let year = today.getFullYear();
      for(let i=0; i<4; i++) {
        let data ={
          star_time:new Date(year,0, 1).getTime(),
          end_time:new Date(year,12, 0).getTime()+(24*60*60-1)*1000,
          title:year+'年'
        };
        year = year-1;
        this.NavItemList.push(data);
      }
      if (this.NavItemList && this.NavItemList[0]) {
        this.start_time = this.NavItemList[0].star_time;
        this.end_time = this.NavItemList[0].end_time;
        this.getSort();
      }
    },
    getAllList(){
      this.NavItemList=[];
      this.start_time =0;
      this.end_time =0;
      let data ={
        isAll:this.isAll,
        title:'合计'
      };
      this.NavItemList.push(data);
      this.getSort();
    },
  //   calculateDates() {
  //     let today = new Date();
  //     let dayOfWeek = today.getDay() || 7; // 获取今天是星期几，getDay()返回0（周日）到6（周六），如果没有返回则默认为7（周日）
  //     let currentWeekStart = new Date(today.setDate(today.getDate() - dayOfWeek + 1)); // 当前周的周一
  //     let lastWeekStart = new Date(currentWeekStart.setDate(currentWeekStart.getDate() - 7)); // 上周的周一
  //     let twoWeeksAgoStart = new Date(lastWeekStart.setDate(lastWeekStart.getDate() - 7)); // 上上周的周一
  //     return {
  //         currentWeekStart,
  //         lastWeekStart,
  //         twoWeeksAgoStart
  //     };
  // },
      //根据当前的日期来计算距离某个特定日期（比如年初）开始的周数
      getNowWeek(dateTime) {
        const today = new Date();
        const startOfYear = new Date(dateTime); // 获取年初的日期
        console.log('getNowWeek - today:', today.getTime(), 'startOfYear:', startOfYear.getTime());
        
        const diffTime = today.getTime() - startOfYear.getTime(); // 计算时间差
        console.log('diffTime:', diffTime);
        
        const daysDifference = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); // 将时间差转换为天数
        console.log('daysDifference:', daysDifference);
        
        const weeksSince = Math.ceil(daysDifference / 7);
        console.log('weeksSince:', weeksSince);
        
        // 如果结果为负数或0，至少返回1周
        return Math.max(1, weeksSince);
      },
      //取输入时间周的周一的时间
      // getNextMonday(dateTime) {
      //   const today = new Date(dateTime);
      //   const day = today.getDay(); // 获取今天是周几，0（周日）到6（周六）
      //   const diff = today.getDate() - day + (day === 0 ? -6 : 1); // 如果今天是周日，则diff为-6，否则为1
      //   const nextMonday = new Date(today.setDate(diff));
      //   return nextMonday;
      // },
      weekCheckingIn(){
        var now = new Date();
        now.setHours(0, 0, 0, 0);
        var nowTime = now.getTime() ;
        var day = now.getDay()|| 7;// 不加 || 7.周末会变成下周一
        var oneDayTime = 24*60*60*1000 ;
        var MondayTime = nowTime - (day-1)*oneDayTime ;//显示周一
        var SundayTime =  nowTime + (7-day)*oneDayTime+(24*60*60-1)*1000 ;//显示周日
        return {MondayTime,SundayTime};
        //调用方法
        // console.log(this.formatDate(new Date(MondayTime)));
        // console.log(this.formatDate(new Date(SundayTime)));
 },
      //格式化日期：yyyy-MM-dd
      formatDate(date) {
          var myyear = date.getFullYear();
          var mymonth = date.getMonth() + 1;
          var myweekday = date.getDate();
          if (mymonth < 10) {
              mymonth = "0" + mymonth;
          }
          if (myweekday < 10) {
              myweekday = "0" + myweekday;
          }
          return (myyear + "-" + mymonth + "-" + myweekday);
      },
      getWeekMonday(dateTime){
        var now = new Date(dateTime);
        now.setHours(0, 0, 0, 0);
        var nowTime = now.getTime() ;
        var day = now.getDay()|| 7;// 不加 || 7.周末会变成下周一
        var oneDayTime = 24*60*60*1000 ;
        var MondayTime = nowTime - (day-1)*oneDayTime ;//显示周一
        return MondayTime;
      },
      hideAgreement() {
        this.contentShow = false;
        // returnTag = false;
      },
      // 判断info文字长度，决定活动商品文字的显示方式
      checkInfoLength() {
        // 首先检查type字段，只有type为1时才显示"活动商品"
        if (this.type !== 1) {
          this.showActivityGoods = false;
          this.activityGoodsNewLine = false;
          return;
        }
        
        if (!this.info) {
          this.showActivityGoods = false;
          this.activityGoodsNewLine = false;
          return;
        }
        
        // 显示活动商品，具体换行方式由checkActualLines决定
        this.showActivityGoods = true;
        console.log('显示活动商品，等待实际行数检查');
      },
      
      // 获取容器实际宽度
      getContainerWidth() {
        // 首先尝试获取实际测量的宽度
        const rulesContent = document.querySelector('.rules-content');
        if (rulesContent) {
          const computedStyle = window.getComputedStyle(rulesContent);
          const clientWidth = rulesContent.clientWidth;
          const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;
          const paddingRight = parseFloat(computedStyle.paddingRight) || 0;
          const actualContentWidth = clientWidth - paddingLeft - paddingRight;
          
          console.log('getContainerWidth - 实际测量宽度:', actualContentWidth + 'px');
          return actualContentWidth;
        }
        
        // 如果无法获取实际宽度，则使用计算方法作为备用
        const screenWidth = window.innerWidth || document.documentElement.clientWidth;
        let cardPadding = 24;
        let maxWidth = 500;
        const availableWidth = screenWidth - 40;
        const actualContainerWidth = Math.min(maxWidth, availableWidth);
        const contentWidth = actualContainerWidth - (cardPadding * 2);
        
        console.log('getContainerWidth - 计算宽度:', contentWidth + 'px');
        return contentWidth;
      },

      // 跳转到活动商品页面
      goToActivityGoods() {
        // 获取当前页面的基础URL
        const currentUrl = window.location.href;
        console.log('当前URL:', currentUrl);
        
        // 提取基础URL部分 (https://yidui.jiujiefang7979.cn/addons)
        const urlMatch = currentUrl.match(/^(https?:\/\/[^\/]+\/addons)/);
        if (urlMatch) {
          const baseUrl = urlMatch[1];
          // 拼接目标URL
          const targetUrl = `${baseUrl}/yun_shop/?menu#/activityGoods?i=1`;
          console.log('目标URL:', targetUrl);
          
          // 跳转到目标页面
          window.location.href = targetUrl;
        } else {
          console.error('无法解析当前URL的基础部分');
          // 如果解析失败，使用默认URL
          window.location.href = 'https://yidui.jiujiefang7979.cn/addons/yun_shop/?menu#/activityGoods?i=1';
        }
      },

      // 跳转到资讯列表页面
      goToNewsList() {
        console.log('跳转到资讯列表');
        this.$router.push({ 
          name: 'newsList', 
          query: { 
            activity_id: this.id,
            activity_name: this.info ? this.info.name : '活动资讯'
          } 
        });
      },

      // 跳转到资讯详情页面
      goToNewsDetail(item) {
        console.log('跳转到资讯详情', item);
        this.$router.push({ 
          name: 'newsDetail', 
          query: { 
            id: item.id,
            activity_id: this.id,
            activity_name: this.info ? this.info.name : '活动资讯'
          } 
        });
      },

      // 跳转到首页
      goToIndex() {
        console.log('跳转到首页');
        this.$router.push({ 
          name: 'index'
        });
      },

      // 关闭弹窗
      hideAgreement() {
        this.contentShow = false;
      },

      // 获取资讯列表
      getNewsListData() {
        const param = {
          activity_id: this.id
        };
        getNewsList(param).then(res => {
          if (res.result == 1 && res.data && res.data.data) {
            // 只取前3条资讯
            this.newsList = res.data.data.slice(0, 3);
          }
        }).catch(err => {
          console.log('获取资讯列表失败', err);
        });
      },

      // 开始检查UID并获取排名
      startCheckUidAndGetRank() {
        console.log('🚀 开始检查UID并获取排名...');
        
        // 立即执行第一次检查
        this.checkAndGetUserRank();
        
        // 如果第一次没有获取到UID，设置定时器每20秒检查一次
        if (!this.$wechatAuth.getUid()) {
          this.uidCheckTimer = setInterval(() => {
            this.uidCheckCount++;
            console.log(`⏰ 第${this.uidCheckCount}次检查UID（最多${this.maxUidCheckCount}次）`);
            
            if (this.uidCheckCount >= this.maxUidCheckCount) {
              console.log('❌ 已达到最大检查次数，停止检查');
              clearInterval(this.uidCheckTimer);
              this.uidCheckTimer = null;
              return;
            }
            
            this.checkAndGetUserRank();
          }, 20000); // 20秒检查一次
        }
      },

      // 检查排行榜中是否有当前用户
      checkMyRankInList() {
        const uid = this.$wechatAuth.getUid();
        
        if (!uid) {
          console.log('⚠️ 未获取到UID，无法检查排名');
          this.showMyRank = false;
          return;
        }
        
        console.log('🔍 在排行榜中查找UID:', uid);
        
        // 在排行榜列表中查找当前用户
        const myRankIndex = this.userList.findIndex(user => user.uid == uid);
        
        if (myRankIndex >= 0) {
          // 找到了，直接使用排行榜中的数据
          const userData = this.userList[myRankIndex];
          
          console.log('✅ 在排行榜中找到用户，直接使用数据:', userData);
          
          this.myInfo = {
            avatar: userData.avatar || 'https://img01.yzcdn.cn/vant/cat.jpeg',
            nickname: userData.nickname || '我的昵称',
            uid: userData.uid || uid,
            amount: userData.amount || 0
          };
          
          this.myRank = myRankIndex + 1;
          this.showMyRank = true;
          
          console.log('✅ 我的排名（从排行榜）:', {
            nickname: this.myInfo.nickname,
            amount: this.myInfo.amount,
            rank: this.myRank
          });
        } else {
          // 没找到，调用接口获取
          console.log('⚠️ 排行榜中未找到用户，调用接口获取');
          this.getUserRankByUid(uid);
        }
      },

      // 检查UID并调用接口获取用户排名
      checkAndGetUserRank() {
        const uid = this.$wechatAuth.getUid();
        
        if (!uid) {
          console.log('⚠️ 未获取到UID，跳过排名查询');
          return;
        }
        
        console.log('✅ 获取到UID:', uid);
        
        // 清除定时器
        if (this.uidCheckTimer) {
          clearInterval(this.uidCheckTimer);
          this.uidCheckTimer = null;
          console.log('✓ UID已获取，停止定时检查');
        }
        
        // 注意：这里不直接调用接口，而是等待排行榜加载完成后由 checkMyRankInList 处理
        console.log('✓ 等待排行榜数据加载完成后自动检查');
      },

      // 通过UID获取用户排名信息
      async getUserRankByUid(uid) {
        // ✅ 再次确认：如果没有UID，不要查询排名
        if (!uid) {
          console.log('⚠️ 没有UID，跳过排名查询');
          this.showMyRank = false;
          return;
        }
        
        try {
          const params = {
            uid: uid,
            id: this.id, // 活动ID
            start_time: this.start_time || '',
            end_time: this.end_time || '',
            isAll: this.isAll || 0
          };
          
          console.log('📡 调用getUserRank接口，参数:', params);
          
          const response = await request({
            url: '/addons/yun_shop/api.php?i=1&scope=pass&route=plugin.activity-set.admin.activity-news.get-user-rank',
            method: 'get',
            params: params
          });
          
          console.log('📥 getUserRank接口返回:', response);
          
          if (response && response.result === 1 && response.data) {
            const userData = response.data;
            
            console.log('✅ 解析到的用户数据:', userData);
            
            // ✅ 修改：适配新的返回数据结构
            this.myInfo = {
              avatar: userData.avatar || 'https://img01.yzcdn.cn/vant/cat.jpeg',
              nickname: userData.nickname || '我的昵称',
              uid: userData.uid || uid,
              amount: userData.amount || 0  // 直接使用 amount 字段
            };
            
            // 使用后端返回的排名
            this.myRank = userData.rank || '-';
            
            // 显示我的排名区域
            this.showMyRank = true;
            
            console.log('✅ 用户排名信息更新成功:', {
              uid: userData.uid,
              nickname: this.myInfo.nickname,
              avatar: this.myInfo.avatar,
              amount: this.myInfo.amount,
              rank: this.myRank,
              dataSource: userData.data_source || 'unknown',
              showMyRank: this.showMyRank
            });
          } else {
            console.warn('⚠️ getUserRank接口返回异常，不显示我的排名');
            this.showMyRank = false;
          }
        } catch (error) {
          console.error('❌ 获取用户排名失败，不显示我的排名:', error);
          this.showMyRank = false;
        }
      },

      // 获取我的排名信息（保留旧方法作为备用）
      getMyRank() {
        const param = {
          activity_id: this.id,
          start_time: this.start_time,
          end_time: this.end_time
        };
        getMyRankInfo(param).then(res => {
          if (res.result == 1 && res.data) {
            this.myRank = res.data.rank || '-';
            this.myInfo = {
              avatar: res.data.avatar || 'https://img01.yzcdn.cn/vant/cat.jpeg',
              nickname: res.data.nickname || '我的昵称',
              uid: res.data.uid || '10000',
              amount: res.data.amount || 0
            };
          }
        }).catch(err => {
          console.log('获取我的排名失败，使用默认数据', err);
        });
      },

      // 更新排行榜人数提示
      updateRankTip() {
        // 检查activityCount是否存在
        if (!this.activityCount) {
          console.log('activityCount为空，不显示排行榜人数提示');
          this.showRankTip = false;
          this.currentRankCount = 0;
          return;
        }

        // 根据当前选中的时间类型获取对应的人数
        const countMap = {
          0: this.activityCount.day,      // 日
          1: this.activityCount.week,     // 周
          2: this.activityCount.month,    // 月
          3: this.activityCount.quarter,  // 季
          4: this.activityCount.year,     // 年
          5: this.activityCount.total    // 累计
        };

        const count = countMap[this.selected];
        
        // 只有当count存在且大于0时才显示提示
        if (count && count > 0 && count !== '0') {
          this.currentRankCount = count;
          this.showRankTip = true;
          console.log(`显示排行榜人数提示: ${count}名 (时间类型: ${this.selected})`);
        } else {
          this.showRankTip = false;
          this.currentRankCount = 0;
          console.log(`不显示排行榜人数提示 (时间类型: ${this.selected}, 人数: ${count})`);
        }
      },

  },
};
